//
//  YYSeraviceDetailVC.m
//  drivingSchool
//
//  Created by 子yu 刘 on 2018/8/18.
//  Copyright © 2018年 子yu 刘. All rights reserved.
//

#import "YYSeraviceDetailVC.h"
#import "YYSerDetailCell1.h"
#import "YYSerDetailCell2.h"
#import "YYSeraviceGoodsDetailVC.h"
#import "YYPayVC.h"

@interface YYSeraviceDetailVC ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>
@property (nonatomic ,strong)NSDictionary * dataDic;
@property (nonatomic ,strong)NSArray * dataArr;

@end

@implementation YYSeraviceDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.lbTag.layer.borderColor = [UIColor colorWithHexString:@"fb2a2a"].CGColor;
    self.lbTag.layer.borderWidth = 0.75;
    self.lbTag.layer.cornerRadius = 2;
    [self getData];
}

- (void)getData{
    [RequestOperationManager serviceDetail_id:self.sid success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            self.dataDic = result[@"data"][@"list"];
            self.dataArr = result[@"data"][@"product"];
            [self reloadData];
        }
        
    } failture:^(NSError *error) {
        
    }];
}

- (void)reloadData{
    [self.bgImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DEF_INTERFACE_WEBVIEWSERVICE,self.dataDic[@"seller_img"]]]];
    self.lbName.text = self.dataDic[@"seller_name"];
    self.lbAdress.text = self.dataDic[@"seller_address"];
    self.lbbuyCount.text = [NSString stringWithFormat:@"%@人购买",self.dataDic[@"sum"]];
    
    [self.tableView reloadData];
}
- (IBAction)call:(id)sender {
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@",self.dataDic[@"seller_phone"]];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = self.dataArr[indexPath.row];
        YYSerDetailCell1 * cell = [tableView dequeueReusableCellWithIdentifier:@"YYSerDetailCell1"];
        cell.lbProject.text = dic[@"name"];
        cell.lbGrade.text =dic[@"grade"];
    if ([dic[@"is_exchange"] isEqualToString:@"3"]||[dic[@"is_exchange"] isEqualToString:@"2"]) {
        if ([dic[@"is_exchange"] isEqualToString:@"2"]) {
            cell.lbSource.text = @"";
            [cell.btnBuy setTitle:@"兑换" forState:UIControlStateNormal];
        }else{
            [cell.btnBuy setTitle:@"购买" forState:UIControlStateNormal];
            cell.lbSource.text = [NSString stringWithFormat:@"￥%@",dic[@"price"]];
        }
        cell.lbSource.textColor = DEF_COLOR_RED;
        cell.lbSource.layer.borderWidth = 0;
    }else{
         if ([dic[@"is_exchange"] isEqualToString:@"0"]) {
             [cell.btnBuy setTitle:@"兑换" forState:UIControlStateNormal];
             cell.lbSource.text = [NSString stringWithFormat:@"%@积分",dic[@"pay_integral"]];
         }else{
             [cell.btnBuy setTitle:@"购买" forState:UIControlStateNormal];
             cell.lbSource.text = [NSString stringWithFormat:@"%@积分+￥%@",dic[@"pay_integral"],dic[@"price"]];
         }
        cell.lbSource.layer.borderWidth = 0.75;
        cell.lbSource.layer.borderColor = DEF_COLOR_MAIN.CGColor;
        cell.lbSource.textColor = DEF_COLOR_MAIN;
        
    }
    
        cell.block = ^{
            if ([dic[@"is_exchange"] isEqualToString:@"1"]||[dic[@"is_exchange"] isEqualToString:@"3"]) {
                [self buyWithDic:dic];
            }else{
                [ASAlertViewController getAlertControllerWithTitle:nil message:[NSString stringWithFormat:@"扣除%@积分",dic[@"pay_integral"]] sureTitle:@"确定" cancelTitle:@"取消" viewController:self sureAction:^(UIAlertAction *action) {
                    [self exchangeWithDic:dic];
                } cancelAction:nil];
                
            }
        };
        return cell;

}

- (void)buyWithDic:(NSDictionary *)dic{
    YYPayVC * pay = (YYPayVC *)[CFUtility getVC:@"YYPayVC" Storyboard:HOME];
    pay.isHidden = YES;
    pay.money = dic[@"price"] ;
    pay.payBlock = ^(NSString *type) {
        [RequestOperationManager serviceProductbuy_product:dic[@"name"] product_id:dic[@"id"] integral:dic[@"pay_integral"] money:dic[@"price"] seller_id:self.sid is_exchange:dic[@"is_exchange"] pay:type success:^(id result) {
            if (DEF_REQ_SUCCESS) {
                if ([type isEqualToString:@"0"]) {
                [self aliPayWithSign:result[@"data"]];
                }else{
                     [self wechatPayWithResponse:result[@"data"]];
                }
            }
        } failture:^(NSError *error) {
            
        }];
    };
    [self.navigationController pushViewController:pay animated:YES];
}

- (void)exchangeWithDic:(NSDictionary *)dic{
    [RequestOperationManager serviceExchange_product:dic[@"name"] product_id:dic[@"id"] integral:dic[@"pay_integral"] is_exchange:dic[@"is_exchange"] seller_id:self.sid success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            [AlertUtil alertMessage:@"兑换成功"];
        }
        
    } failture:^(NSError *error) {
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YYSeraviceGoodsDetailVC * goodsDetail = (YYSeraviceGoodsDetailVC *)[CFUtility getVC:@"YYSeraviceGoodsDetailVC" Storyboard:SERAVICE];
    goodsDetail.gid = self.dataArr[indexPath.row][@"id"];
    [self.navigationController pushViewController:goodsDetail animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80.0;
}

-(NSDictionary *)dataDic{
    if (!_dataDic) {
        _dataDic = [NSDictionary dictionary];
    }
    return _dataDic;
}
-(NSArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSArray array];
    }
    return _dataArr;
}



- (void)wechatPayWithResponse:(NSDictionary *)response {
    PayReq* req  = [[PayReq alloc] init];
    req.partnerId = response[@"partnerid"];
    req.prepayId= response[@"prepayid"];
    req.package = response[@"package"];
    req.nonceStr= response[@"noncestr"];
    req.timeStamp= [response[@"timestamp"] intValue];
    req.sign=response[@"sign"];
    [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        
        if (errCode == FLErrCodeSuccess) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
        }
    }];
}

- (void)aliPayWithSign:(NSString * )sign{
    /**
     *  @author gitKong
     *
     *  来自支付宝文档数据
     */
    
    [FLPAYMANAGER fl_payWithOrderMessage:sign callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        if (resultDic&&[resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
            
        }
        
    }];
    
    
}


- (NSString *)jumpToBizPay {
    //============================================================
    /**
     *  @author Clarence
     *
     *  来自微信文档数据
     */
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                
                [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
                    NSLog(@"errCode = %zd,errStr = %@",errCode,errStr);
                }];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
    
}
@end
